package com.edu.hbwe.book.servlet.client;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

import com.edu.hbwe.book.entity.User;
import com.edu.hbwe.book.exception.RegisterException;
import com.edu.hbwe.book.service.UserService;
import com.edu.hbwe.book.service.impl.UserServiceImpl;
import com.edu.hbwe.book.util.ActiveCodeUtils;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		System.out.println(request.getParameter("gender"));
		
		//1.校验验证码
		String usercode=request.getParameter("userCode");

		System.out.println(usercode); 
		String serverCode=(String)request.getSession().getAttribute("serverCode");
		System.out.println(serverCode);
		if (!serverCode.equalsIgnoreCase(usercode)) {
			response.getWriter().write("输入验证码错误");
//			request.setAttribute("codeError","输入验证码错误");
//			request.getRequestDispatcher("/client/register.jsp").forward(request,response); 
			return;
		}

		// 将表单提交的数据封装到javaBean
		User user = new User();
		try {

			BeanUtils.populate(user, request.getParameterMap());
			// 封裝激活码

			user.setActiveCode(ActiveCodeUtils.createActiveCode());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		// 调用service完成注册操作。
		UserService service = new UserServiceImpl();
		try {
			service.register(user);

		} catch (RegisterException e) {
			e.printStackTrace();

			response.getWriter().write(e.getMessage());
			return;

		}
		// 注册成功，跳转到registersuccess.jsp
		response.sendRedirect(request.getContextPath() + "/client/registersuccess.jsp");
		return;
	}
}
